<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="药库ID" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          placeholder="请选择药库"
          clearable
          filterable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in warehouseOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="药品ID" prop="drugId">
        <el-select
          v-model="queryParams.drugId"
          placeholder="请选择药品"
          clearable
          filterable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in drugOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:drug_warehouse_operate:add']"
        >新增入库</el-button>
      </el-col>

      <!-- 隐藏修改按钮，但不删除 -->
      <el-col :span="1.5" v-if="false">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:drug_warehouse_operate:edit']"
        >修改出库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehouse:drug_warehouse_operate:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehouse:drug_warehouse_operate:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drug_warehouse_operateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作记录" align="center" prop="operateId" />
      <el-table-column label="药库ID" align="center" prop="warehouseId" />
      <el-table-column label="药品ID" align="center" prop="drugId" />

      <!-- 修改药库ID列 -->
      <el-table-column label="药库ID" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.warehouseId }} ({{ getWarehouseName(scope.row.warehouseId) }})</span>
        </template>
      </el-table-column>
      <!-- 修改药品ID列 -->
      <el-table-column label="药品ID" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.drugId }} ({{ getDrugName(scope.row.drugId) }})</span>
        </template>
      </el-table-column>

      <el-table-column label="操作类型" align="center" prop="operateType">
        <template slot-scope="scope">
          <span>{{ scope.row.operateType === 1 ? '入库' : scope.row.operateType === 2 ? '出库' : '未知' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作数量" align="center" prop="quantity" />
      <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:drug_warehouse_operate:edit']"
          >修改</el-button>  <!--隐藏修改按钮，但不删除-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['warehouse:drug_warehouse_operate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药库操作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="药库ID" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择药库" clearable filterable>
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="药品ID" prop="drugId">
          <el-select v-model="form.drugId" placeholder="请选择药品" clearable filterable>
            <el-option
              v-for="item in drugOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 操作类型字段设置为只读 -->
        <el-form-item label="操作类型" prop="operateType" v-if="title === '添加药库操作'">
          <el-select v-model="form.operateType" placeholder="请选择操作类型" clearable disabled>
            <!-- 只显示入库选项 -->
            <el-option
              v-for="item in operateTypeOptions"
              v-if="item.value === 1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="操作类型" prop="operateType" v-else>
          <el-select v-model="form.operateType" placeholder="请选择操作类型" clearable disabled>
            <!-- 只显示入库选项 -->
            <el-option
              v-for="item in operateTypeOptions"
              v-if="item.value === 2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入操作数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDrug_warehouse_operate, getDrug_warehouse_operate, delDrug_warehouse_operate, addDrug_warehouse_operate, updateDrug_warehouse_operate } from "@/api/warehouse/drug_warehouse_operate"
// 新增API调用
import { listDrug_warehouse } from "@/api/warehouse/drug_warehouse" // 假设有这个API
import { listDrug } from "@/api/pharmacy/drug" // 假设有这个API

export default {
  name: "Drug_warehouse_operate",
  data() {
    return {
      // 新增映射数据
      warehouseMap: new Map(), // 药库ID到名称的映射
      drugMap: new Map(),      // 药品ID到名称的映射

      // 新增下拉选项数据
      warehouseOptions: [], // 药库下拉选项
      drugOptions: [], // 药品下拉选项

      // 操作类型选项
      operateTypeOptions: [
        {
          value: 1,
          label: '入库'
        },
        {
          value: 2,
          label: '出库'
        }
      ],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药库操作表格数据
      drug_warehouse_operateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        drugId: null,
        operateType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "药库ID不能为空", trigger: "blur" }
        ],
        drugId: [
          { required: true, message: "药品ID不能为空", trigger: "blur" }
        ],
        operateType: [
          { required: true, message: "操作类型不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "操作数量不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getWarehouseOptions() // 加载药库选项
    this.getDrugOptions() // 加载药品选项
  },
  methods: {
    /** 获取药库下拉选项 */
    /** 获取药库下拉选项并建立映射 */
    getWarehouseOptions() {
      listDrug_warehouse({
        pageSize: 1000,
        isValid: 1 // 只查询启用的药库
      }).then(response => {
        this.warehouseOptions = response.rows.map(item => ({
          value: item.warehouseId,
          label: `${item.warehouseName} (ID: ${item.warehouseId})`
        }))

        // 建立ID到名称的映射
        response.rows.forEach(item => {
          this.warehouseMap.set(item.warehouseId, item.warehouseName)
        })
      })
    },
    /** 获取药品下拉选项 */

    /** 获取药品下拉选项并建立映射 */
    getDrugOptions() {
      listDrug({ pageSize: 1000 }).then(response => {
        this.drugOptions = response.rows.map(item => ({
          value: item.drugId,
          label: `${item.drugName} (ID: ${item.drugId})`
        }))

        // 建立ID到名称的映射
        response.rows.forEach(item => {
          this.drugMap.set(item.drugId, item.drugName)
        })
      })
    },

    /** 根据药库ID获取药库名称 */
    getWarehouseName(warehouseId) {
      return this.warehouseMap.get(warehouseId) || '未知药库'
    },

    /** 根据药品ID获取药品名称 */
    getDrugName(drugId) {
      return this.drugMap.get(drugId) || '未知药品'
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加药库操作"
      // 设置默认操作类型为入库
      this.$set(this.form, 'operateType', 1)

      // 确保选项已加载
      if (this.warehouseOptions.length === 0) {
        this.getWarehouseOptions()
      }
      if (this.drugOptions.length === 0) {
        this.getDrugOptions()
      }
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const operateId = row.operateId || this.ids
      getDrug_warehouse_operate(operateId).then(response => {
        this.form = response.data
        // 强制设置为出库操作
        this.$set(this.form, 'operateType', 2)
        this.open = true
        this.title = "修改药库操作"
      })
    },

    /** 查询药库操作列表 */
    getList() {
      this.loading = true
      listDrug_warehouse_operate(this.queryParams).then(response => {
        this.drug_warehouse_operateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        operateId: null,
        warehouseId: null,
        drugId: null,
        operateType: null,
        quantity: null,
        operateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.operateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.operateId != null) {
            updateDrug_warehouse_operate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDrug_warehouse_operate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const operateIds = row.operateId || this.ids
      this.$modal.confirm('是否确认删除药库操作编号为"' + operateIds + '"的数据项？').then(function() {
        return delDrug_warehouse_operate(operateIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/drug_warehouse_operate/export', {
        ...this.queryParams
      }, `drug_warehouse_operate_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
